package com.atguigu.gmall.order.handler.impl;

import com.atguigu.gmall.common.execption.GmallException;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.feign.product.SkuDetailFeignClient;
import com.atguigu.gmall.order.handler.AbstractOrderHandler;
import com.atguigu.gmall.order.dto.DetailDto;
import com.atguigu.gmall.order.dto.OrderSubmitDto;
import com.atguigu.gmall.product.entity.SkuInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;

@Component
@Slf4j
public class PriceValidOrderHandler extends AbstractOrderHandler {

    @Autowired
    private SkuDetailFeignClient skuDetailFeignClient ;

    @Override
    public int sort() {
        return 2;
    }

    @Override
    public String process(OrderSubmitDto orderSubmitDto, String tradeNo) {

        // 校验价格
        List<DetailDto> detailDtoList = orderSubmitDto.getOrderDetailList();
        long count = detailDtoList.stream().filter(detailDto -> {
            BigDecimal orderPrice = detailDto.getOrderPrice();
            Result<SkuInfo> infoResult = skuDetailFeignClient.findSkuInfoBySkuId(detailDto.getSkuId());
            SkuInfo skuInfo = infoResult.getData();
            return !orderPrice.equals(skuInfo.getPrice());
        }).count();
        if(count > 0) {
            throw new GmallException(ResultCodeEnum.ORDER_INFO_PRICE_ERROR) ;
        }


        AbstractOrderHandler abstractOrderHandler = this.getNext();
        if(abstractOrderHandler != null) {
            return abstractOrderHandler.process(orderSubmitDto , tradeNo) ;
        }
        return null;
    }
}
